package com.ruoyi.ai.service.impl;

import com.ruoyi.ai.domain.MedicineQuestion;
import com.ruoyi.ai.domain.MedicineQuestionParam;
import com.ruoyi.ai.mapper.MedicineQuestionMapper;
import com.ruoyi.ai.mapper.MedicineQuestionParamMapper;
import com.ruoyi.ai.service.IMedicineQuestionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 问诊记录Service实现
 * 
 * @author AI
 */
@RequiredArgsConstructor
@Service
public class MedicineQuestionServiceImpl implements IMedicineQuestionService {

    private final MedicineQuestionMapper medicineQuestionMapper;
    private final MedicineQuestionParamMapper medicineQuestionParamMapper;

    /**
     * 保存问诊记录
     * 
     * @param params 问诊参数
     * @param aiResponse AI回复内容
     * @param model AI模型
     * @param msgType 消息类型
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveMedicineQuestion(Map<String, String> params, String aiResponse, String model, String msgType) {
        MedicineQuestion medicineQuestion = new MedicineQuestion();
        
        // 设置原始内容
        StringBuilder originalContent = new StringBuilder();
        for (Map.Entry<String, String> item : params.entrySet()) {
            originalContent.append(item.getKey()).append("答:").append(item.getValue()).append("。");
        }
        medicineQuestion.setOriginalContent(originalContent.toString());
        
        // 设置AI回复和模型信息
        medicineQuestion.setAiResponse(aiResponse);
        medicineQuestion.setAiModel(model);
        medicineQuestion.setMsgType(msgType);
        
        // 保存问诊记录主表
        boolean result = medicineQuestionMapper.insert(medicineQuestion) > 0;
        
        // 保存问诊参数明细
        if (result) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                MedicineQuestionParam param = new MedicineQuestionParam();
                param.setQuestionId(medicineQuestion.getId());
                param.setParamKey(entry.getKey());
                param.setParamValue(entry.getValue());
                medicineQuestionParamMapper.insert(param);
            }
        }
        
        return result;
    }

    /**
     * 新增问诊记录
     * 
     * @param medicineQuestion 问诊记录
     * @return 结果
     */
    @Override
    public int insertMedicineQuestion(MedicineQuestion medicineQuestion) {
        return medicineQuestionMapper.insert(medicineQuestion);
    }
}